#include "FlashModule.h"

#include "SimpleCompletion.h"

#include <string.h>

// 注意，spi1-0是eeprom，不是flash

// flash 1存储
Flash_Ctrl_Def flash_1_ctrl;

// w25q 取消写保护
rt_err_t Flash_Write_Enable_Interface(Flash_Ctrl_Def* obj) {
	rt_err_t res = RT_EOK;
  // 锁定资源。
  if (strlen(obj->spi_ch_obj.spi_lock.parent.parent.name) != 0) {// 只有初始化了保护锁才会检查
    uint8_t get_mutex = 0;
    while (rt_mutex_take(&(obj->spi_ch_obj.spi_lock), 50 * (2 ^ get_mutex)) != RT_EOK) {
      if (get_mutex >= 3) {
        return RT_EBUSY;
      }
      get_mutex++;
    }
  }
	
	if (strlen(obj->spi_ch_obj.spi_lock.parent.parent.name) != 0) {// 只有初始化了保护锁才会检查
    rt_mutex_release(&(obj->spi_ch_obj.spi_lock));
  }
  return res;
}// w25q 取消写保护

// DMA1 CH6 传输完成中断
// SPI1 FLASH DMA
void INT_SRC_DMA1_TC6_IrqCallback(void) {
  DMA_ChCmd(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, DISABLE);
  SPI_Cmd(flash_1_ctrl.spi_ch_obj.spi_cm, DISABLE);

  // 处理各阶段发送完成
  if (flash_1_ctrl.spi_ch_obj.spi_translate_status == SPI_TRANSLATE_CMD) {// 命令字节发送完成
    if (flash_1_ctrl.spi_ch_obj.send_size > 0) { // 发送数据命令
      flash_1_ctrl.spi_ch_obj.spi_translate_status = SPI_TRANSLATE_SEND;
      // 设置发送通道
      DMA_SetSrcAddr(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, (uint32_t) (flash_1_ctrl.spi_ch_obj.spi_data_buf));
      DMA_SetTransCount(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, flash_1_ctrl.spi_ch_obj.send_size);
      // 发送使能
      DMA_ChCmd(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, ENABLE);
      SPI_Cmd(flash_1_ctrl.spi_ch_obj.spi_cm, ENABLE);
    } else if ( flash_1_ctrl.spi_ch_obj.recv_size > 0 ) { // 接收数据命令
			// 配置接收触发
			AOS_SetTriggerEventSrc(AOS_DMA1_6, EVT_SRC_SPI1_SPRI);
			flash_1_ctrl.spi_ch_obj.spi_translate_status = SPI_TRANSLATE_RECV;
			// 设置发送通道
      DMA_SetSrcAddr(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, (uint32_t) (flash_1_ctrl.spi_ch_obj.spi_data_buf));
      DMA_SetTransCount(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, flash_1_ctrl.spi_ch_obj.recv_size);
      // 发送使能
      DMA_ChCmd(flash_1_ctrl.spi_ch_obj.cm_dma, flash_1_ctrl.spi_ch_obj.ch_dma, ENABLE);
      SPI_Cmd(flash_1_ctrl.spi_ch_obj.spi_cm, ENABLE);
		} else { // 如果仅仅是命令发送，则自动置为空操作，结束循环
			flash_1_ctrl.spi_ch_obj.spi_translate_status = SPI_TRANSLATE_IDLE;
		}
		// 如果仅仅是
  }// 处理各阶段发送完成

	// 如果确定不接任何数据阶段，则直接返回
	if ( flash_1_ctrl.spi_ch_obj.spi_translate_status != SPI_TRANSLATE_CMD ) {
		flash_1_ctrl.spi_ch_obj.spi_translate_status = SPI_TRANSLATE_IDLE;
		completion_done(&(flash_1_ctrl.spi_ch_obj.spi_transport_sem));
	}
}
